<template>
  <BaseDialog v-model="dialogVisible" :title="$t('route.costCalculator')" width="1000px" :before-close="handleClose">
    <el-form ref="refDialogForm" v-loading="formLoading" class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'" :model="formData" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('travelAgency.templateName')" prop="name">
            <TextInput v-model="formData.name" clearable :label="$t('travelAgency.templateName')" :maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('travelAgency.tripDays')" prop="tripDays">
            <TextInput v-model="formData.tripDays" verify-type="nzint" clearable :label="$t('travelAgency.tripDays')"
              :maxlength="4" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('travelAgency.defaultPersonCount')" prop="peopleCount">
            <TextInput v-model="formData.peopleCount" verify-type="nzint" clearable
              :label="$t('travelAgency.defaultPersonCount')" :maxlength="4" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item required>
            <template #label>
              <label>{{ $t('travelAgency.applicableAge') }}</label>
            </template>
            <div style="display: flex; align-items: center">
              <el-form-item prop="ageMin">
                <TextInput v-model="formData.ageMin" verify-type="int" clearable
                  :label="$t('travelAgency.applicableAge')" :maxlength="3" @blur="handleAgeBlur('ageMin')" />
              </el-form-item>
              <span style="width: 50px; text-align: center"> -- </span>
              <el-form-item prop="ageMax">
                <TextInput v-model="formData.ageMax" verify-type="int" clearable
                  :label="$t('travelAgency.applicableAge')" :maxlength="3" @blur="handleAgeBlur('ageMax')" />
              </el-form-item>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="0" style="margin-bottom: 0">
            <el-button type="primary" style="margin-bottom: 10px" @click="handleAddCostItem">{{ $t('public.add')
              }}</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="0" class="form-item-table" prop="itemList">
            <BaseTable ref="refContentTable" v-loading="tableLoading" :data="tableData" show-summary
              :summary-method="getSummaries" :span-method="arraySpanMethod" max-height="calc(100vh - 272px)"
              row-key="id">
              <TableColumn prop="day" :label="$t('travelAgency.days')" :column-width="routeColumnWidth.day">
                <template #default="{ row }">
                  <span>{{
                    g_t('travelAgency.dayI', {
                    i: g_nzhcn.encodeS(row.day)
                    })
                    }}</span>
                </template>
              </TableColumn>
              <TableColumn prop="address" :label="$t('travelAgency.location')"
                :column-width="routeColumnWidth.address" />
              <TableColumn prop="name" :label="$t('travelAgency.project')" :column-width="routeColumnWidth.name" />
              <TableColumn prop="type" min-width="80" :label="$t('travelAgency.type')"
                :column-width="routeColumnWidth.type">
                <template #default="{ row }">
                  <span>{{
                    g_options.getOptionText(
                    g_options.costItemTypeOptions,
                    row.type,
                    '--'
                    )
                    }}</span>
                </template>
              </TableColumn>
              <TableColumn prop="count" min-width="80" :label="$t('travelAgency.quantity')"
                :column-width="routeColumnWidth.count">
                <template #default="{ row }">
                  <div style="
                      display: flex;
                      justify-content: center;
                      align-items: center;
                    ">
                    <span>{{ row.count }}</span>
                    <el-tooltip v-if="row.countFlag" :content="$t('travelAgency.followGroupSize')" placement="top"
                      effect="light">
                      <el-icon><i-ep-QuestionFilled /></el-icon>
                    </el-tooltip>
                  </div>
                </template>
              </TableColumn>
              <TableColumn prop="price" min-width="80" :label="$t('hotel.unitPrice')"
                :column-width="routeColumnWidth.price" />
              <TableColumn prop="exchangeRate" min-width="80" :label="$t('travelAgency.exchangeRate')"
                :column-width="routeColumnWidth.exchangeRate" />
              <TableColumn prop="totalPrice" min-width="80" :label="$t('travelAgency.totalPrice')"
                :column-width="routeColumnWidth.totalPrice" />
              <TableColumn prop="perCapitaPrice" :label="$t('travelAgency.perCapitaPrice')"
                :column-width="routeColumnWidth.perCapitaPrice" />
              <TableColumn fixed="right" prop="action" min-width="190" :label="$t('public.action')"
                :column-width="routeColumnWidth.action">
                <template #default="{ row, $index }">
                  <el-button text @click="handleEdit(row, $index)">
                    {{ $t('public.edit') }}
                  </el-button>
                  <el-button text @click="handleDelete(row, $index)">{{
                    $t('public.delete')
                    }}</el-button>
                  <el-button text :disabled="!$index" @click="handleMoveUp(row, $index)">{{ $t('travelAgency.moveUp')
                    }}</el-button>
                  <el-button text :disabled="$index === tableData.length - 1" @click="handleMoveDown(row, $index)">{{
                    $t('travelAgency.moveDown') }}</el-button>
                </template>
              </TableColumn>
            </BaseTable>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
          }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
          }}</el-button>
      </div>
    </template>
  </BaseDialog>
  <AddCostItem v-if="addCostItemVisible" v-model="addCostItemVisible" :row="costItem" :type="costItemType"
    :tripDays="formData.tripDays" @add="handleAddTravelCb" @update="handleUpdateTravelCb" />
</template>

<script setup>
import AddCostItem from './AddCostItem.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  name: '',
  tripDays: '',
  peopleCount: '',
  ageMin: '',
  ageMax: '',
  totalPrice: 0,
  perPersonPrice: 0,
  itemList: []
})
const rules = {
  name: g_rules.commonInputText(g_t('travelAgency.templateName')),
  peopleCount: g_rules.commonInputText(g_t('travelAgency.defaultPersonCount')),
  ageMin: g_rules.startAge(formData.value, 'endAge', refDialogForm),
  ageMax: g_rules.endAge(formData.value, 'startAge', refDialogForm),
  itemList: [
    {
      required: true,
      message: g_t('travelAgency.pleaseAddLocationInfo'),
      trigger: ['blur', 'change']
    }
  ]
}
const refContentTable = ref(null)
const tableLoading = ref(false)
const routeColumnWidth = ref({})
const addCostItemVisible = ref(false)
const costItem = ref({})
const costItemType = ref('add')
const costItemTableIndex = ref(0)

const tableData = computed(() => {
  const { itemList, peopleCount } = formData.value
  return itemList.map(item => {
    let count = item.count
    // if (!(item.count === '' && peopleCount === '')) {
    //   count = (count ?? peopleCount) || 0
    // }
    if (item.count === '') {
      count = peopleCount
      item.countFlag = 1 // 0-不跟随出团人数，1-跟随出团人数
    }
    const totalPrice = g_utils.getFloat(count * item.price * item.exchangeRate)
    return {
      ...item,
      count,
      totalPrice,
      perCapitaPrice: peopleCount
        ? g_utils.getFloat(totalPrice / peopleCount)
        : '--'
    }
  })
})

watch(
  () => tableData.value,
  nv => {
    setTimeout(() => {
      useTableColumnWidth({
        refTable: refContentTable.value
      }).getTableColumnWidth(data => {
        routeColumnWidth.value = data
      })
    })
  },
  {
    immediate: true,
    deep: true
  }
)

watch(
  () => tableData.value,
  nv => {
    nextTick(() => {
      refDialogForm.value.validateField('itemList')
    })
  },
  {
    deep: true
  }
)

onMounted(() => {
  props.type === 'edit' && getFormData()
})

const getSummaries = param => {
  // console.log('getSummaries', param)
  console.log('tableData.value', tableData.value)
  const result = tableData.value.reduce(
    (acc, curr) => {
      acc.totalPrice += curr.totalPrice * 1
      if (curr.type + '' === '1' || curr.type + '' === '8') {
        acc.carGuidePrice += curr.totalPrice * 1
      } else if (curr.type + '' === '2') {
        acc.mealPrice += curr.totalPrice * 1
      } else if (curr.type + '' === '3') {
        acc.roomPrice += curr.totalPrice * 1
      }
      return acc
    },
    { totalPrice: 0, carGuidePrice: 0, mealPrice: 0, roomPrice: 0 }
  )
  console.log('getSummaries-result', result)
  const showPrice = data => {
    return formData.value.peopleCount
      ? g_utils.getFloat(data / formData.value.peopleCount)
      : '--'
  }
  formData.value.totalPrice = g_utils.getFloat(result.totalPrice)
  formData.value.perPersonPrice = showPrice(result.totalPrice)
  return [
    `${g_t('travelAgency.totalPrice')}：${formData.value.totalPrice}`,
    '',
    `${g_t('travelAgency.perCapitaTotalPrice')}：${formData.value.perPersonPrice
    }`,
    '',
    `${g_t('travelAgency.perCapitaVehicleGuidePrice')}：${showPrice(
      result.roomPrice
    )}`,
    '',
    `${g_t('travelAgency.perCapitaMealPrice')}：${showPrice(result.carGuidePrice)}`,
    '',
    `${g_t('travelAgency.perCapitaRoomPrice')}：${showPrice(result.mealPrice)}`,
    ''
  ]
}

const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // console.log(
  //   'row, column, rowIndex, columnIndex',
  //   row,
  //   column,
  //   rowIndex,
  //   columnIndex
  // )
  nextTick(() => {
    if (refContentTable.value.$el) {
      const current = refContentTable.value.$el
        .querySelector('.el-table__footer-wrapper')
        .querySelector('.el-table__footer')
      const cell = current.rows[0].cells
      // 定义要合并的列规则：起始索引 & 合并个数
      const mergeRules = [
        { index: 0, span: 2 }, // 合并第 0 列，跨 2 列
        { index: 2, span: 2 },
        { index: 4, span: 2 },
        { index: 6, span: 2 },
        { index: 8, span: 2 }
      ]

      // 执行合并与样式设置
      mergeRules.forEach(rule => {
        const { index, span } = rule
        if (cell[index]) {
          cell[index].colSpan = span
          cell[index].style.textAlign = 'center'

          // 隐藏后续被合并的单元格
          for (let i = 1; i < span; i++) {
            if (cell[index + i]) {
              cell[index + i].style.display = 'none'
            }
          }
        }
      })
      // 修改单元格的样式
      for (let i = 0; i < cell.length; i++) {
        cell[i].style.color = i === 0 ? '#6fba2c' : '#333'
      }
    }
  })
}

const getFormData = _ => {
  g_api.travelAgency
    .apiCalculatorDetail({ templateId: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = {
          ...formData.value,
          id: ''
        }
        g_utils.assignFormData(formData.value, data)
        console.log('formData.value', formData.value)
      }
    })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleAddCostItem = _ => {
  addCostItemVisible.value = true
  costItemType.value = 'add'
}

const handleAgeBlur = prop => {
  //
}

const handleAddTravelCb = data => {
  console.log('handleAddTravelCb-data', data)
  formData.value.itemList.push(data)
}

const handleUpdateTravelCb = data => {
  console.log('handleUpdateTravelCb-data', data)
  formData.value.itemList.splice(costItemTableIndex.value, 1, data)
}

const handleEdit = (row, i) => {
  addCostItemVisible.value = true
  costItem.value = row
  costItemType.value = 'edit'
  costItemTableIndex.value = i
}

const handleDelete = (row, i) => {
  formData.value.itemList.splice(i, 1)
}

const handleMoveUp = (row, i) => {
  handleDelete(row, i)
  formData.value.itemList.splice(i - 1, 0, row)
}

const handleMoveDown = (row, i) => {
  handleDelete(row, i)
  formData.value.itemList.splice(i + 1, 0, row)
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.travelAgency.apiCalculatorCreate
        : g_api.travelAgency.apiCalculatorUpdate
    urlMethod({
      templateInfo: {
        ...formData.value,
        itemList: undefined
      },
      itemList: formData.value.itemList
    })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
